package com.yuanfeng.order.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.*;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.vo.job.AcquiescenceVO;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import com.yuanfeng.order.dto.GoodsParaDTO;
import com.yuanfeng.order.dto.ShopParaDTO;
import com.yuanfeng.order.entity.OrderGoodsEntity;
import com.yuanfeng.order.entity.OrderGoodsEvaluationEntity;
import com.yuanfeng.order.mapper.OrderGoodsEvaluationMapper;
import com.yuanfeng.order.mapper.OrderGoodsMapper;
import com.yuanfeng.order.service.OrderGoodsEvaluationService;
import com.yuanfeng.order.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName OrderGoodsEvaluationServiceImpl
 * @Description 商品评论表
 * @Author cyp
 * @Date 2023-05-26 13:28:36
 * @Version 1.0
 **/
@Service
public class OrderGoodsEvaluationServiceImpl extends ServiceImpl<OrderGoodsEvaluationMapper, OrderGoodsEvaluationEntity>
        implements OrderGoodsEvaluationService {

    @Resource
    private OrderGoodsMapper orderGoodsMapper;

    @Resource
    private OrderGoodsEvaluationMapper orderGoodsEvaluationMapper;

    @Override
    public ResponseResult queryCommentsCount(Integer commonId) {
        return ResponseResult.success(this.baseMapper.queryCommentsCount(commonId));
    }

    @Override
    public ResponseResult getComments(Map<String, Object> map) {
        ResponseResult rr = new ResponseResult();
        PagedByCommentsVO pi = new PagedByCommentsVO();
        Integer commonId = (Integer) map.get("commonId");
        Integer evaluation = (Integer) map.get("evaluation");
        String resultNum = null;
        String imageNum = null;
        if (evaluation == 2) {
            resultNum = "good";
        } else if (evaluation == 3) {
            resultNum = "neutral";
        } else if (evaluation == 4) {
            resultNum = "bad";
        } else if (evaluation == 5) {
            imageNum = "";
        }
        map.put("resultNum",resultNum);
        map.put("imageNum",imageNum);
        IPage<CommentsEntityVO> page = this.baseMapper.commentsQuery(new Query<CommentsEntityVO>().getPage(map),map);
        List<CommentsEntityVO> commentsQueryList = page.getRecords();
        for (int i = 0; i < commentsQueryList.size(); i++) {
            CommentsEntityVO ce = new CommentsEntityVO();
            ce = commentsQueryList.get(i);
            Integer additionalDay = DateUtils.differentDaysByMillisecond(ce.getCreateTime(),ce.getAdditionalContentTime());
            ce.setAdditionalDay(additionalDay);
            // 方法描述 隐藏用户名中间位置字符，显示前后1个字符
            if(ce.getIsanonymous() == 1){
                String userName = ce.getUserName();
                String name = userName.substring(0, 1) + "****" + userName.substring(userName.length() - 1, userName.length());
                ce.setUserName(name);
            }
            if (ce.getImage() != null) {
                String[] imagesList = ce.getImage().replace(" ", "").split(",");
                for (int j = 0; j < imagesList.length; j++) {
                    if (ce.getImage() == "") {
                        String[] emptyList = {};
                        ce.setImagesList(emptyList);
                    } else {
                        ce.setImagesList(imagesList);
                    }
                }
                if(ce.getAdditionalImage() != null){
                    String[] additionalImagesList = ce.getAdditionalImage().replace(" ", "").split(",");
                    for (int j = 0; j < additionalImagesList.length; j++) {
                        if (ce.getAdditionalImage() == "") {
                            String[] emptyList = {};
                            ce.setAdditionalImagesList(emptyList);
                        } else {
                            ce.setAdditionalImagesList(additionalImagesList);
                        }
                    }
                }else{
                    String[] images = {};
                    ce.setAdditionalImagesList(images);
                }
            } else {
                String[] images = {};
                ce.setImagesList(images);
            }
        }
        page.setRecords(commentsQueryList);
        //中评数
        Integer neutralTotalCount = this.baseMapper.getEvaluationTotalCount(commonId,"neutral");
        //差评数
        Integer badTotalCount = this.baseMapper.getEvaluationTotalCount(commonId,"bad");
        //晒单数
        Integer imageTotalCount = this.baseMapper.getEvaluationTotalCount(commonId,"image");
        //好评数
        Integer goodsOrderNum = this.baseMapper.getEvaluationTotalCount(commonId,"good");
        //所有评论
        Integer allOrderNum = this.baseMapper.getEvaluationTotalCount(commonId,null);
        BigDecimal aon = new BigDecimal(allOrderNum);
        BigDecimal gon = new BigDecimal(goodsOrderNum);
        String rate = null;
        BigDecimal num = new BigDecimal(100);
        try {
            if (allOrderNum == 0) {
                rr.setCode(2);
                rr.setMessage("该商品暂时无评论！");
            } else {
                rate =  (gon.divide(aon,2,BigDecimal.ROUND_HALF_UP).multiply(num)).toString()+ "%";
            }
        } catch (Exception e) {
            return ResponseResult.fail(e.getMessage());
        }
        //好评率
        pi.setRate(rate);
        pi.setAllOrderNum(allOrderNum);
        pi.setBadTotalCount(badTotalCount);
        pi.setGoodTotalCount(goodsOrderNum);
        pi.setNeutralTotalCount(neutralTotalCount);
        pi.setImageTotalCount(imageTotalCount);
        pi.setRecords(PageUtils.getPage(page));
        //列表数据
        //result.put("data",PageUtils.getPage(page));
        //result.put("pi",pi);

        return ResponseResult.success(pi);
    }

    @Override
    public ResponseResult queryMyEvaluation(Map<String, Object> map) {
        String token = (String) map.get("token");
        UserInfoVO userInfoVO = ParseTokenUtils.getUserInfoByToken(token);
        if (userInfoVO != null) {
            try {
                String userId = userInfoVO.getUserId();
                // 1:全部评价,2:晒图评价
                Integer type = (Integer) map.get("type");

                // 分页查询评价信息
                IPage<OrderGoodsEvaluationEntity> page = this.baseMapper.selectPage(new Query<OrderGoodsEvaluationEntity>().getPage(map), new LambdaQueryWrapper<OrderGoodsEvaluationEntity>()
                        .eq(type == 2, OrderGoodsEvaluationEntity::getResult, "good")
                        .eq(type == 3, OrderGoodsEvaluationEntity::getResult, "neutral")
                        .eq(type == 4, OrderGoodsEvaluationEntity::getResult, "bad")
                        .ne(type == 5, OrderGoodsEvaluationEntity::getImage, "")
                        .eq(OrderGoodsEvaluationEntity::getUserId, userId)
                        .orderByDesc(OrderGoodsEvaluationEntity::getCreateTime));

                List<OrderGoodsEvaluationEntity> records = page.getRecords();
                PageUtils pageUtils = PageUtils.getPage(page);

                /**
                 * 封装数据
                 */
                List<MyEvaluationVO> evaluationList = new ArrayList<>();
                if (CollectionUtils.isNotEmpty(records)) {
                    evaluationList = records.stream().map(entity -> {
                        MyEvaluationVO catResult = new MyEvaluationVO();

                        BeanUtils.copyProperties(entity, catResult);
                        return catResult;
                    }).collect(Collectors.toList());
                }

                for (MyEvaluationVO mep : evaluationList) {
                    Integer additionalDay = DateUtils.differentDaysByMillisecond(mep.getCreateTime(), mep.getAdditionalContentTime());

                    mep.setAdditionalDay(additionalDay);

                    OrderGoodsEntity orderGoodsEntity = orderGoodsMapper.selectOne(new LambdaQueryWrapper<OrderGoodsEntity>()
                            .eq(OrderGoodsEntity::getGoodsId, mep.getGoodsId()).orderByDesc(OrderGoodsEntity::getCreateTime).last("limit 1"));

                    String goodImage = orderGoodsEntity.getGoodsImage();
                    mep.setGoodsImage(goodImage);
                    if (mep.getImage() != null) {
                        String[] imagesList = mep.getImage().replace(" ", "").split(",");
                        for (int j = 0; j < imagesList.length; j++) {
                            if ("".equals(mep.getImage())) {
                                String[] emptyList = {};
                                mep.setImagesList(emptyList);
                            } else {
                                mep.setImagesList(imagesList);
                            }
                        }
                        if (mep.getAdditionalImage() != null) {
                            String[] addItionalImagesList = mep.getAdditionalImage().replace(" ", "").split(",");
                            for (int j = 0; j < addItionalImagesList.length; j++) {
                                if ("".equals(mep.getAdditionalImage())) {
                                    String[] emptyList = {};
                                    mep.setAdditionalImagesList(emptyList);
                                } else {
                                    mep.setAdditionalImagesList(addItionalImagesList);
                                }
                            }
                        }
                    }
                }
                pageUtils.setList(evaluationList);
                return ResponseResult.success(pageUtils);
            } catch (Exception e) {
                return ResponseResult.fail(e.getMessage());
            }
        } else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
    }

    @Override
    public ResponseResult platFormBuyerComments(GoodsParaDTO goodsPara) {
        //将对象转换为map
        Map data = null;
        try {
            data = ParseMapUtils.beanToMap(goodsPara);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        //分页查询数据
        IPage<GoodsCommentsVO> page = this.baseMapper.selectGoodsComments(new Query<GoodsCommentsVO>().getPage(data),goodsPara);
        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult platFormShopComments(ShopParaDTO goodsPara) {
        //将参数转为map
        Map data = null;
        try {
            data = ParseMapUtils.beanToMap(goodsPara);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        IPage<ShopCommentsVO> page = this.baseMapper.selectShopComments(new Query<ShopCommentsVO>().getPage(data), goodsPara);
        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult deleteBuyerComments(Map<String, String> map) {
        int delete = this.baseMapper.deleteById(map.get("evaluation_goods_id"));
        if (delete > 0){
            return ResponseResult.success(BizCodeEnume.DELETE_SUCCESS);
        }
        return ResponseResult.fail(BizCodeEnume.DELETE_ERROR);
    }

    @Override
    public ResponseResult deleteShopComments(Map<String, String> map) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(map.get("token"));
        if (null == userInfo) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        this.baseMapper.deleteShopComments(map);
        return ResponseResult.success();
    }

    @Override
    public ResponseResult getAllComments(Map<String, Object> map) {
        String token = (String) map.get("token");
        boolean isExistToken = RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + token);
        if (!isExistToken) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        try {
            UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(token);
            String shopId = ui.getShopId();
            Integer evaluation = (Integer) map.get("evaluation");
            String resultNum = null;
            String imageNum = null;
            if (evaluation == 1) {
                resultNum = "";
            } else if (evaluation == 2) {
                resultNum = "'good'";
            } else if (evaluation == 3) {
                resultNum = "'neutral'";
            } else if (evaluation == 4) {
                resultNum = "'bad'";
            } else if (evaluation == 5) {
                imageNum = "";
            }
            map.put("shopId", shopId);
            map.put("resultNum", resultNum);
            map.put("imageNum", imageNum);
            Page<CommentsEntityVO> page = new Page<>((Integer) map.get("page"), (Integer) map.get("limit"));
            IPage<CommentsEntityVO> CommentsQueryList = orderGoodsEvaluationMapper.commentsQuery(page, map);
            for (CommentsEntityVO record : CommentsQueryList.getRecords()) {

                // 方法描述 隐藏用户名中间位置字符，显示前后1个字符
                String userName = record.getUserName();
                String name = userName.substring(0, 1) + "****"
                        + userName.substring(userName.length() - 1, userName.length());
                //record.setUserName(name);
                if (record.getImage() != null) {
                    String[] imagesList = record.getImage().replace(" ", "").split(",");
                    for (int j = 0; j < imagesList.length; j++) {
                        if (record.getImage() == "") {
                            String[] emptyList = {};
                            record.setImagesList(emptyList);
                        } else {
                            record.setImagesList(imagesList);
                        }
                    }
                    if (record.getAdditionalImage() != null) {
                        String[] additionalImagesList = record.getAdditionalImage().replace(" ", "").split(",");
                        for (int j = 0; j < additionalImagesList.length; j++) {
                            if (record.getAdditionalImage() == "") {
                                String[] emptyList = {};
                                record.setAdditionalImagesList(emptyList);
                            } else {
                                record.setAdditionalImagesList(imagesList);
                            }
                        }
                    }
                }
            }
            return ResponseResult.success(PageUtils.getPage(CommentsQueryList));
        } catch (Exception e) {
            return ResponseResult.fail(500, "GetAllCommentsErrorResults:" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public ResponseResult replyToComment(Map<String, Object> map) {
        String token = (String) map.get("token");
        boolean isExistToken = RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + token);
        if (!isExistToken) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        map.put("updateTime",TimeStampUtil.getNowDate());
        boolean isUpdateForReply = this.baseMapper.updateForReply(map);
        if (isUpdateForReply) {
            return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
        }
        return ResponseResult.fail(BizCodeEnume.OPERATION_FAILED);
    }

    @Override
    @Transactional
    public ResponseResult add(Map<String, Object> map) {
        String token = (String) map.get("token");
        boolean isExistToken = RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + token);
        if (!isExistToken) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        map.put("updateTime",TimeStampUtil.getNowDate());
        boolean isUpdateForReply = this.baseMapper.updateForAdditionalReply(map);
        if (isUpdateForReply) {
            return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
        }
        return ResponseResult.fail(BizCodeEnume.OPERATION_FAILED);
    }

    @Override
    public ResponseResult insertEvaluated(AcquiescenceVO acquiescenceVO) {
        OrderGoodsEvaluationEntity evaluationEntity=new OrderGoodsEvaluationEntity();
        BeanUtils.copyProperties(acquiescenceVO, evaluationEntity);
        evaluationEntity.setUserId(acquiescenceVO.getBuyerUserId());
        int flag=this.baseMapper.insert(evaluationEntity);
        if(flag==1){
            return  ResponseResult.success();
        }else {
            return  ResponseResult.fail();
        }
    }
}
